#include "Pixie.h"


generic module BitsToByteP(uint8_t bitMask) {
  provides interface PixieStage;
  uses interface PixieSink;
  uses interface PixieMemAlloc;

} implementation {
  uint8_t value = 0;
  command error_t PixieStage.init() {
    value = 0;
    return SUCCESS;
  }

  command error_t PixieStage.run(memref_t dequeuedMR) {
    memref_t newMR = PIXIE_NULL_MEMREF;
    uint8_t *ptrVal;
    if (dequeuedMR == PIXIE_NULL_MEMREF) {
      return FAIL;
    } else {
      uint8_t newVal = (uint8_t*) call PixieMemAlloc.data(dequeuedMR); 
      if(newVal > 0) {
        value = value|(255&bitMask);
      }
      else if(newVal == 0) {
        value = value&(255^bitMask)
      }
      newMR = call PixieMemAlloc.allocate(sizeof(uint8_t)); 
      ptrVal = call PixieMemAlloc.data(newMR); 
      *ptrVal = value;
    }

    call PixieSink.enqueue(newMR); //pass the new memref downstream
    call PixieMemAlloc.release(newMR); //must release memref after done
    call PixieMemAlloc.release(dequeuedMR); //must release memref after done
    return SUCCESS;
  }
}
